package fr.cephb.operonj.core.db.comparator;

import java.math.BigInteger;
import java.util.Comparator;

import com.sleepycat.bind.tuple.StringBinding;
import com.sleepycat.bind.tuple.TupleInput;

public class SmartComparator
	implements Comparator<byte[]>
	{
	public SmartComparator()
		{
		
		}
	
    public int compare(byte[] ba, byte[] bb)
        {
        StringBinding bind= new StringBinding();
        String a=  bind.entryToObject(new TupleInput(ba));
        String b=  bind.entryToObject(new TupleInput(bb));
       
        String ss[]={a.toString(),b.toString()};
        char c[]={0,0};
        int i[]={0,0};
        while(true)
            {
            if(i[0] == a.length() &&
               i[1] == b.length()) return 0;
            if(i[0] == a.length()) return -1;
            if(i[1] == b.length()) return 1;

            c[0]=Character.toUpperCase(a.charAt(i[0]));
            c[1]=Character.toUpperCase(b.charAt(i[1]));

            //search for integer
            if( Character.isDigit(c[0]) &&
                Character.isDigit(c[1]))
                {
                int j[]={i[0]+1,i[1]+1};
                
                BigInteger values[]={null,null};
                for(int side=0;side<2;++side)
                    {
                    while(  j[side]< ss[side].length() &&
                            Character.isDigit(ss[side].charAt(j[side])))
	                    {
	                    j[side]++;
	                    }
                    values[side]=new BigInteger(ss[side].substring(i[side],j[side]));
                    }
                int k=values[0].compareTo(values[1]);
                i[0]=j[0];
                i[1]=j[1];
                if(k!=0) return k;
                continue;
                }

            int k=c[0]-c[1];
            if(k!=0) return (k<0?-1:1);
            i[0]++;
            i[1]++;
            }
        }

	}
